﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using News.CYT369.Com.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace News.CYT369.Com.Controllers
{
    class UpperCaseNamingPolicy : System.Text.Json.JsonNamingPolicy
    {
        public override string ConvertName(string name)
        {
            return name;
        }
    }

    [SystemExceptionProcessor]
    public class BaseController : Controller
    {
        public static object s_lock_object = new object();

        public News.CYT369.Com.Models.UserSession UserSession {
            get {
                return this.HttpContext.RequestServices.GetService(typeof(News.CYT369.Com.Models.UserSession)) as News.CYT369.Com.Models.UserSession;
            }
        }

        public ContentResult Content(bool b)
        {
            return base.Content(b.ToString().ToLower());
        }

        public JsonResult DefaultJson(object obj)
        {
            var setting = new System.Text.Json.JsonSerializerOptions()
            {
                PropertyNamingPolicy = new UpperCaseNamingPolicy()
            };


            return base.Json(obj, setting);
        }
    }

    public class AllowAnonymousController : BaseController
    {
    }

    [Authorize]
    public class AuthorizeController : BaseController
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (this.User.Identity.IsAuthenticated)
            {
                if (this.UserSession.GetSessionUser() == null)
                {
                    var s = Uri.EscapeDataString(context.HttpContext.Request.Path.ToString()+context.HttpContext.Request.QueryString.ToString());
                    Response.Redirect(Url.Content($"~/Account/Login?returnUrl={s}&force=true"));
                }
                else
                {
                    base.OnActionExecuting(context);
                }
            }
            else
            {
                base.OnActionExecuting(context);
            }
        }

    }

}
